package cn.tedu._03vehicle.base.filter;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/v1/vehicle/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("初始化过滤器LoginCheckFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入登录状态校验的过滤器...");
        // 获取Session对象
        //父类用子类的方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO != null){
            log.debug("用户已登录，允许访问");
            filterChain.doFilter(request,response);
        }else {
            log.debug("用户未登录，请先登录！");
            response.sendRedirect("/login.html");
        }
    }

    @Override
    public void destroy() {
        log.debug("销毁过滤器LoginCheckFilter");
    }
}
